﻿using System;
using System.Text;
using System.Windows.Forms;
using static WindowsFormsApp1.userWin.WindowsHook;
using System.Runtime.InteropServices;
using WindowsFormsApp1.Common;
using System.Drawing;

namespace WindowsFormsApp1.userWin
{

    public partial class UserControl1 : UserControl
    {
        //程序的窗口
        IntPtr WinformPtr;
        UserControl1 User;
        GCHandle gch;
        int HHOOK = 0;
        public UserControl1()
        {
            User = this;
            InitializeComponent();
        }

        private void UserControl1_Load(object sender, EventArgs e)
        {


            // int i = new MyEvenDemo().Stop(hoohid);
        }

        //hHook变量记录返回的句柄，如果hHook不为0则说明钩子安装成功。
        //键盘钩子程序
        public int KeyBoardHookProc(int nCode, IntPtr wParam, IntPtr lParam, int hHook)
        {
            if (nCode >= 0)
            {
                KeyBoardHookStruct kbh = (KeyBoardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyBoardHookStruct));
                Keys key = (Keys)Enum.Parse(typeof(Keys), kbh.vkCode.ToString());
                User.InputIn.Text = key.ToString();

                if (kbh.vkCode == (int)Keys.F5)  // 截获F5
                {
                    IntPtr myPtr = GetForegroundWindow();
                    SetNowWindows(User, myPtr);
                }
                if (kbh.vkCode == (int)Keys.S && (int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Shift)  //截获Ctrl+Shift+S 
                {
                    MessageBox.Show("No Save");
                    return 0;
                }
            }
            return CallNextHookEx(hHook, nCode, wParam, lParam);
        }
        void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Space)
            {
                this.button1.PerformClick();
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            IntPtr myPtr = GetForegroundWindow();
            if (WinformPtr != myPtr)
            {
                SetFocus(WinformPtr);
                ShowWindowAsync(WinformPtr, 9);
            }
        }

        private void SetWindows(UserControl1 user, IntPtr myPtr)
        {
            RECT rect = new RECT();
            GetWindowRect(myPtr, ref rect);
            int width = rect.Right - rect.Left;                        //窗口的宽度
            user.width.Text = width.ToString();
            int height = rect.Bottom - rect.Top;                   //窗口的高度
            user.height.Text = height.ToString();
            int x = rect.Left;
            user.left.Text = x.ToString();
            int y = rect.Top;
            user.top.Text = y.ToString();
            StringBuilder title = new StringBuilder(256);
            GetWindowText(myPtr, title, title.Capacity);//得到窗口的标题 
            StringBuilder className = new StringBuilder(256);
            GetClassName(myPtr, className, className.Capacity);//得到窗口的句柄 
            user.WindName.Text = title.ToString();
            user.WindId.Text = myPtr.ToString();
        }

        private void SetNowWindows(UserControl1 user, IntPtr myPtr)
        {
            RECT rect = new RECT();
            GetWindowRect(myPtr, ref rect);
            int width = rect.Right - rect.Left;                        //窗口的宽度
            user.widthNow.Text = width.ToString();
            int height = rect.Bottom - rect.Top;                   //窗口的高度
            user.heightNow.Text = height.ToString();
            int x = rect.Left;
            user.leftNow.Text = x.ToString();
            int y = rect.Top;
            user.topNow.Text = y.ToString();
            StringBuilder title = new StringBuilder(256);
            GetWindowText(myPtr, title, title.Capacity);//得到窗口的标题 
            StringBuilder className = new StringBuilder(256);
            GetClassName(myPtr, className, className.Capacity);//得到窗口的句柄 
            user.windNameNow.Text = title.ToString();
            user.windIdNow.Text = myPtr.ToString();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

            if (checkBox1.Checked)
            {
                timer1.Start();
            }
            else
            {
                timer1.Stop();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.button1.Text == "开始获取句柄")
            {
                IntPtr WinformPtr = GetForegroundWindow();
                SetWindows(User, WinformPtr);
                HHOOK = new MyEvenDemo().Start(13, KeyBoardHookProc, 0, out gch);
                this.button1.Text = "结束获取句柄";
            }
            else
            {
                int hoohid = new MyEvenDemo().Stop(HHOOK, gch);
                this.button1.Text = "开始获取句柄";
            }


        }


        private void injection_Click(object sender, EventArgs e)
        {
            try
            {
                IntPtr myPtr = new IntPtr(Convert.ToInt64(this.windIdNow.Text));
                var key = (Keys)Enum.Parse(typeof(Keys), this.inputout.Text);
                //Win32API.PostMessage(hwndTest, 0x65, 3, ref cds);
                //MessageAPI.WM_DEADCHAR  WM_CHAR
                var time = Convert.ToInt32(outputtime.Text);
                uint keyValue = new MyEvenDemo().MapWindowVirtualKey(Convert.ToUInt32(key), 0);
                uint lParam = (keyValue << 16) + 1;
                new MyEvenDemo().postWindowsMessage(myPtr, new IntPtr(MessageAPI.WM_KEYDOWN), new IntPtr(Convert.ToUInt32(key)), new IntPtr(lParam));
                new MyEvenDemo().WiteTime(time, delegateMethod, myPtr, new IntPtr(MessageAPI.WM_KEYUP), new IntPtr(Convert.ToUInt32(key)), new IntPtr(lParam));
            }
            catch (Exception)
            {
                this.remark.Text = "出错了";
            }
        }
        public void delegateMethod(IntPtr hwnd, IntPtr wMsg, IntPtr wParam, IntPtr lParam)
        {
            new MyEvenDemo().postWindowsMessage(hwnd, wMsg, wParam, lParam);
            return;
        }
        private delegate void richTextBoxCallBack();
        public void SetText(Control control, string s)
        {
            richTextBoxCallBack callback = delegate ()//使用委托 
            {
                control.Text = s;
            };
            control.Invoke(callback);
        }

        /// <summary>
        /// 注入文本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            IntPtr myPtr = new IntPtr(Convert.ToInt64(windIdNow.Text));
            string str = intext.Text;
            new MyEvenDemo().setTextMessage(myPtr, str);
        }

        /// <summary>
        /// 对比图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void img_company_Click(object sender, EventArgs e)
        {
            var parentPath = this.parent_img.Text;
            var childPath = this.child_img.Text;
            if (string.IsNullOrEmpty(this.parent_img.Text))
            {
                parentPath = "../../img/12.jpeg";
            }
            if (string.IsNullOrEmpty(this.child_img.Text))
            {
                childPath = "../../img/12_s.jpeg";
            }
            Bitmap parentf = new Bitmap(parentPath);
            Bitmap childf = new Bitmap(childPath);
            //获取相似度
            double simble= string.IsNullOrEmpty(this.simble.Text)?90: Convert.ToDouble(this.simble.Text);
            //是0.5还是50
            int h = simble <= 1 ? Convert.ToInt32(simble * 100) : Convert.ToInt32(simble);
            //图片对比
            Point point=FileDll.FindPic(parentf, childf, h); 
            this.parent_top.Text = point.Y.ToString();
            this.parent_left.Text = point.X.ToString();
        }

        private void img_DC_Click(object sender, EventArgs e)
        {
            IntPtr intp1 = new IntPtr(Convert.ToInt64(windIdNow.Text));
            string s = "ScreenShot/1.jpg";
            new MyEvenDemo().ScreenShot(intp1, s);
        }
    }
}
